<template>
  <view class="match-model-form-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <text class="page-title">{{ isEditing ? '编辑模式' : '创建模式' }}{{ matchName ? ` - ${matchName}` : '' }}</text>
    </view>
    
    <!-- 表单内容 -->
    <view class="form-container">
      <view class="form-section">
        <view class="section-title">基本信息</view>
        
        <view class="form-item">
          <text class="form-label">赛事ID *</text>
          <input 
            class="form-input" 
            v-model="formData.matchId" 
            placeholder="请输入赛事ID"
            :disabled="!!matchName"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">赛事模型名称 *</text>
          <input 
            class="form-input" 
            v-model="formData.matchModelName" 
            placeholder="请输入赛事模型名称"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">名称模板 *</text>
          <input 
            class="form-input" 
            v-model="formData.nameTemplate" 
            placeholder="请输入名称模板，支持{{year}}、{{type}}等变量"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">赛程模型ID *</text>
          <view class="form-picker" @click="openScheduleModelPicker">
            <view class="picker-text">{{ selectedScheduleModelName || '请选择赛程模式' }}</view>
            <view class="picker-arrow">▼</view>
          </view>
        </view>
      </view>
      
      <view class="form-section">
        <view class="section-title">创建配置</view>
        
        <view class="form-item">
          <text class="form-label">赛程创建类型</text>
          <view class="form-picker" @click="openCreateTypePicker">
            <view class="picker-text">{{ createTypeOptions[createTypeIndex] }}</view>
            <view class="picker-arrow">▼</view>
          </view>
        </view>
        
        <view class="form-item">
          <text class="form-label">触发类型</text>
          <view class="form-picker" @click="openTriggerTypePicker">
            <view class="picker-text">{{ triggerTypeOptions[triggerTypeIndex] }}</view>
            <view class="picker-arrow">▼</view>
          </view>
        </view>
      </view>
      
      <view class="form-section">
        <view class="section-title">时间设置</view>
        
        <view class="form-item">
          <text class="form-label">下次触发时间</text>
          <view class="time-picker-row">
            <picker 
              mode="date" 
              :value="nextTriggerDate" 
              @change="onNextTriggerDateChange"
              class="date-picker"
            >
              <view class="picker-text">{{ nextTriggerDate || '选择日期' }}</view>
            </picker>
            <picker 
              mode="time" 
              :value="nextTriggerTime" 
              @change="onNextTriggerTimeChange"
              class="time-picker"
            >
              <view class="picker-text">{{ nextTriggerTime || '选择时间' }}</view>
            </picker>
          </view>
        </view>
        
        <view class="form-item">
          <text class="form-label">比赛开始时间</text>
          <view class="time-picker-row">
            <picker 
              mode="date" 
              :value="matchStartDate" 
              @change="onMatchStartDateChange"
              class="date-picker"
            >
              <view class="picker-text">{{ matchStartDate || '选择日期' }}</view>
            </picker>
            <picker 
              mode="time" 
              :value="matchStartTime" 
              @change="onMatchStartTimeChange"
              class="time-picker"
            >
              <view class="picker-text">{{ matchStartTime || '选择时间' }}</view>
            </picker>
          </view>
        </view>
        
        <view class="form-item">
          <text class="form-label">比赛结束时间</text>
          <view class="time-picker-row">
            <picker 
              mode="date" 
              :value="matchEndDate" 
              @change="onMatchEndDateChange"
              class="date-picker"
            >
              <view class="picker-text">{{ matchEndDate || '选择日期' }}</view>
            </picker>
            <picker 
              mode="time" 
              :value="matchEndTime" 
              @change="onMatchEndTimeChange"
              class="time-picker"
            >
              <view class="picker-text">{{ matchEndTime || '选择时间' }}</view>
            </picker>
          </view>
        </view>
        
        <view class="form-item">
          <text class="form-label">比赛持续时间（分钟）</text>
          <input 
            class="form-input" 
            v-model="formData.matchDurationTime" 
            type="number"
            placeholder="请输入比赛持续时间（分钟）"
          />
        </view>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="submit-section">
      <button class="submit-btn" @click="submitForm" :disabled="submitting">
        {{ submitting ? '提交中...' : (isEditing ? '更新' : '创建') }}
      </button>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="loading">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
    </view>
    
    <!-- 赛程模式选择弹出框 -->
    <view class="modal-overlay" v-if="showScheduleModelPicker" @click="closeScheduleModelPicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择赛程模式</text>
          <button class="close-btn" @click="closeScheduleModelPicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="model in scheduleModelList" 
            :key="model.id"
            @click="selectScheduleModel(model)"
            :class="{ 'selected': formData.matchScheduleModelId === model.id }"
          >
            <text class="option-text">{{ model.matchScheduleModelName || model.nameTemplate || `模式${model.id}` }}</text>
            <view class="option-check" v-if="formData.matchScheduleModelId === model.id">✓</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 创建方式选择弹出框 -->
    <view class="modal-overlay" v-if="showCreateTypePicker" @click="closeCreateTypePicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择创建方式</text>
          <button class="close-btn" @click="closeCreateTypePicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in createTypeOptions" 
            :key="index"
            @click="selectCreateType(index)"
            :class="{ 'selected': createTypeIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="createTypeIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 触发类型选择弹出框 -->
    <view class="modal-overlay" v-if="showTriggerTypePicker" @click="closeTriggerTypePicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择触发类型</text>
          <button class="close-btn" @click="closeTriggerTypePicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in triggerTypeOptions" 
            :key="index"
            @click="selectTriggerType(index)"
            :class="{ 'selected': triggerTypeIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="triggerTypeIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchModelAPI, MatchScheduleModelAPI } from '@/api/battle.js'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const isEditing = ref(false)
const modelId = ref('')
const matchName = ref('') // 赛事名称
const createTypeIndex = ref(0)
const triggerTypeIndex = ref(0)

// 选择器相关数据
const showScheduleModelPicker = ref(false)
const showCreateTypePicker = ref(false)
const showTriggerTypePicker = ref(false)
const scheduleModelList = ref([])
const selectedScheduleModelName = ref('')

// 直接在页面上显示的时间选择器数据
const nextTriggerDate = ref('')
const nextTriggerTime = ref('')
const matchStartDate = ref('')
const matchStartTime = ref('')
const matchEndDate = ref('')
const matchEndTime = ref('')

// 表单数据
const formData = ref({
  matchId: '',                              // 赛事ID（必填）
  matchModelName: '',                       // 赛事模型名称（必填）
  matchScheduleModelId: '',                 // 赛程模型ID（必填）
  nameTemplate: '',                         // 名称模板（可选）
  matchScheduleCreateType: 0,               // 赛程创建类型（可选）
  triggerType: 0,                           // 触发类型（可选）
  nextTriggerTime: null,                    // 下次触发时间（时间戳，可选）
  matchStartTime: null,                     // 比赛开始时间（时间戳，可选）
  matchEndTime: null,                        // 比赛结束时间（时间戳，可选）
  matchDurationTime: null                    // 比赛持续时间（分钟）
})

// 创建方式选项
const createTypeOptions = ['手动创建', '自动创建', '定时创建']
const createTypeMap = {
  0: 0, // 手动创建
  1: 1, // 自动创建
  2: 2  // 定时创建
}

// 触发类型选项
const triggerTypeOptions = ['每日触发', '每周触发', '每月触发', '自定义触发']
const triggerTypeMap = {
  0: 1, // 每日触发
  1: 2, // 每周触发
  2: 3, // 每月触发
  3: 0  // 自定义触发
}

// 页面加载
onLoad((options) => {
  // 如果URL中有赛事ID参数，预填充到表单中
  if (options.matchId) {
    formData.value.matchId = options.matchId
  }
  
  // 如果URL中有赛事名称参数，保存用于显示
  if (options.matchName) {
    matchName.value = decodeURIComponent(options.matchName)
  }
  
  if (options.mode === 'edit' && options.id) {
    isEditing.value = true
    modelId.value = options.id
    loadModelData()
  }
})

// 加载模式数据（编辑模式）
const loadModelData = async () => {
  if (!modelId.value) return
  
  loading.value = true
  try {
    console.log('开始加载模式数据，ID:', modelId.value)
    
    // 使用page接口查询详情，通过matchModelId筛选
    const result = await MatchModelAPI.page({
      matchModelId: modelId.value,
      pageNum: 0,
      pageSize: 1
    })
    
    console.log('API返回结果:', result)
    
    if (result.code === 0 && result.data) {
      const modelList = result.data.list || result.data || []
      console.log('查询到的模式列表:', modelList)
      
      if (modelList.length > 0) {
        const model = modelList[0]
        console.log('找到模式数据:', model)
        
        // 映射数据到表单
        formData.value = {
          matchId: model.matchId || model.id || '',
          matchModelName: model.matchModelName || '',
          matchScheduleModelId: model.matchScheduleModelId || '',
          nameTemplate: model.nameTemplate || '',
          matchScheduleCreateType: model.matchScheduleCreateType || 0,
          triggerType: model.triggerType || 0,
          nextTriggerTime: model.nextTriggerTime || null,
          matchStartTime: model.matchStartTime || null,
          matchEndTime: model.matchEndTime || null,
          matchDurationTime: model.matchDurationTime || null
        }
        
        console.log('映射后的表单数据:', formData.value)
        
        // 初始化时间选择器
        initTimePickers()
        
        // 设置创建类型索引
        createTypeIndex.value = model.matchScheduleCreateType || 0
        console.log('设置创建类型索引:', createTypeIndex.value)
        
        // 设置触发类型索引
        const triggerTypeValue = model.triggerType || 0
        triggerTypeIndex.value = Object.values(triggerTypeMap).indexOf(triggerTypeValue)
        if (triggerTypeIndex.value === -1) triggerTypeIndex.value = 0
        console.log('设置触发类型索引:', triggerTypeIndex.value, '原始值:', triggerTypeValue)
        
        // 设置选中的赛程模式名称
        if (model.matchScheduleModelId) {
          selectedScheduleModelName.value = model.matchScheduleModelName || `模式${model.matchScheduleModelId}`
          console.log('设置选中的赛程模式名称:', selectedScheduleModelName.value)
        }
        
        console.log('数据加载完成')
        
        // 强制更新响应式数据
        await nextTick()
        console.log('强制更新后的表单数据:', formData.value)
      } else {
        throw new Error('未找到指定的模式数据')
      }
    } else {
      throw new Error(result.msg || '获取模式数据失败')
    }
  } catch (error) {
    console.error('加载模式数据失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.matchId.trim()) {
    uni.showToast({
      title: '请输入赛事ID',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.matchModelName.trim()) {
    uni.showToast({
      title: '请输入赛事模型名称',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.matchScheduleModelId.trim()) {
    uni.showToast({
      title: '请选择赛程模型',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.nameTemplate.trim()) {
    uni.showToast({
      title: '请输入名称模板',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const api = isEditing.value ? MatchModelAPI.edit : MatchModelAPI.create
    
    // 构建提交数据
    const submitData = { ...formData.value }
    
    // 如果是编辑模式，需要传入matchModelId
    if (isEditing.value) {
      submitData.matchModelId = modelId.value
    }
    
    const result = await api(submitData)
    
    if (result.code === 0) {
      uni.showToast({
        title: isEditing.value ? '更新成功' : '创建成功',
        icon: 'success'
      })
      
      // 延迟返回，让用户看到成功提示
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      throw new Error(result.msg || (isEditing.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 赛程模式选择器相关函数
const openScheduleModelPicker = async () => {
  showScheduleModelPicker.value = true
  await loadScheduleModelList()
}

const closeScheduleModelPicker = () => {
  showScheduleModelPicker.value = false
}

const selectScheduleModel = (model) => {
  formData.value.matchScheduleModelId = model.id
  selectedScheduleModelName.value = model.matchScheduleModelName || model.nameTemplate || `模式${model.id}`
  closeScheduleModelPicker()
}

// 创建方式选择器相关函数
const openCreateTypePicker = () => {
  showCreateTypePicker.value = true
}

const closeCreateTypePicker = () => {
  showCreateTypePicker.value = false
}

const selectCreateType = (index) => {
  createTypeIndex.value = index
  formData.value.matchScheduleCreateType = createTypeMap[index]
  closeCreateTypePicker()
}

// 触发类型选择器相关函数
const openTriggerTypePicker = () => {
  showTriggerTypePicker.value = true
}

const closeTriggerTypePicker = () => {
  showTriggerTypePicker.value = false
}

const selectTriggerType = (index) => {
  triggerTypeIndex.value = index
  formData.value.triggerType = triggerTypeMap[index]
  closeTriggerTypePicker()
}

// 直接在页面上显示的时间选择器事件处理函数
const onNextTriggerDateChange = (e) => {
  nextTriggerDate.value = e.detail.value
  updateNextTriggerTime()
}

const onNextTriggerTimeChange = (e) => {
  nextTriggerTime.value = e.detail.value
  updateNextTriggerTime()
}

const onMatchStartDateChange = (e) => {
  matchStartDate.value = e.detail.value
  updateMatchStartTime()
}

const onMatchStartTimeChange = (e) => {
  matchStartTime.value = e.detail.value
  updateMatchStartTime()
}

const onMatchEndDateChange = (e) => {
  matchEndDate.value = e.detail.value
  updateMatchEndTime()
}

const onMatchEndTimeChange = (e) => {
  matchEndTime.value = e.detail.value
  updateMatchEndTime()
}

// 更新时间戳的函数
const updateNextTriggerTime = () => {
  if (nextTriggerDate.value && nextTriggerTime.value) {
    const dateTimeStr = `${nextTriggerDate.value} ${nextTriggerTime.value}`
    formData.value.nextTriggerTime = new Date(dateTimeStr).getTime()
  }
}

const updateMatchStartTime = () => {
  if (matchStartDate.value && matchStartTime.value) {
    const dateTimeStr = `${matchStartDate.value} ${matchStartTime.value}`
    formData.value.matchStartTime = new Date(dateTimeStr).getTime()
  }
}

const updateMatchEndTime = () => {
  if (matchEndDate.value && matchEndTime.value) {
    const dateTimeStr = `${matchEndDate.value} ${matchEndTime.value}`
    formData.value.matchEndTime = new Date(dateTimeStr).getTime()
  }
}

// 加载赛程模式列表
const loadScheduleModelList = async () => {
  try {
    const result = await MatchScheduleModelAPI.page({
      pageNum: 0,
      pageSize: 100
    })
    
    if (result.code === 0 && result.data) {
      scheduleModelList.value = result.data.list || result.data || []
    } else {
      scheduleModelList.value = []
      throw new Error(result.msg || '获取赛程模式列表失败')
    }
  } catch (error) {
    console.error('获取赛程模式列表失败:', error)
    uni.showToast({
      title: error.message || '获取赛程模式列表失败',
      icon: 'none'
    })
  }
}

// 初始化时间选择器
const initTimePickers = () => {
  // 初始化下次触发时间
  if (formData.value.nextTriggerTime) {
    const date = new Date(formData.value.nextTriggerTime)
    nextTriggerDate.value = formatDate(date)
    nextTriggerTime.value = formatTime(date)
  }
  
  // 初始化比赛开始时间
  if (formData.value.matchStartTime) {
    const date = new Date(formData.value.matchStartTime)
    matchStartDate.value = formatDate(date)
    matchStartTime.value = formatTime(date)
  }
  
  // 初始化比赛结束时间
  if (formData.value.matchEndTime) {
    const date = new Date(formData.value.matchEndTime)
    matchEndDate.value = formatDate(date)
    matchEndTime.value = formatTime(date)
  }
}

// 格式化日期和时间函数
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const formatTime = (date) => {
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}
</script>

<style lang="scss" scoped>
.match-model-form-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  
  .back-btn {
    background: none;
    border: none;
    color: #fff;
    font-size: 28rpx;
    padding: 10rpx 20rpx;
    margin-right: 20rpx;
  }
  
  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
  }
}

.form-container {
  .form-section {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 30rpx;
      padding-bottom: 15rpx;
      border-bottom: 2rpx solid #eee;
    }
    
    .form-item {
      margin-bottom: 30rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .form-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 15rpx;
        font-weight: bold;
      }
      
      .form-input {
        width: 100%;
        height: 80rpx;
        border: 2rpx solid #eee;
        border-radius: 12rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        background: #fff;
        box-sizing: border-box;
        
        &:focus {
          border-color: #667eea;
        }
      }
      
      .form-picker {
        width: 100%;
        height: 80rpx;
        border: 2rpx solid #eee;
        border-radius: 12rpx;
        padding: 0 20rpx;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        
        .picker-text {
          font-size: 28rpx;
          color: #333;
        }
        
        .picker-arrow {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
}

.submit-section {
  margin-top: 40rpx;
  
  .submit-btn {
    width: 100%;
    height: 80rpx;
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    border: none;
    border-radius: 12rpx;
    color: #fff;
    font-size: 28rpx;
    font-weight: bold;
    
    &:disabled {
      opacity: 0.6;
    }
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .loading-content {
    background: #fff;
    border-radius: 20rpx;
    padding: 60rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #667eea;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }
    
    .loading-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 选择器弹出框样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .picker-modal-content {
    width: 90%;
    max-height: 80%;
    background: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    
    .picker-modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #eee;
      
      .picker-modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        width: 60rpx;
        height: 60rpx;
        border: none;
        background: none;
        font-size: 40rpx;
        color: #999;
      }
    }
    
    .picker-modal-body {
      padding: 30rpx;
      max-height: 60vh;
      overflow-y: auto;
      
      .picker-option {
        padding: 20rpx;
        background: #f8f9fa;
        border-radius: 12rpx;
        margin-bottom: 15rpx;
        border: 2rpx solid transparent;
        position: relative;
        cursor: pointer;
        
        &.selected {
          border-color: #007bff;
          background: #e3f2fd;
        }
        
        .option-text {
          font-size: 28rpx;
          color: #333;
        }
        
        .option-check {
          position: absolute;
          top: 10rpx;
          right: 10rpx;
          font-size: 24rpx;
          color: #007bff;
          font-weight: bold;
        }
      }
    }
  }
}

// 直接在页面上显示的时间选择器样式
.time-picker-row {
  display: flex;
  gap: 20rpx;
  
  .date-picker, .time-picker {
    flex: 1;
    height: 80rpx;
    border: 2rpx solid #eee;
    border-radius: 12rpx;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    box-sizing: border-box;
    
    .picker-text {
      font-size: 28rpx;
      color: #333;
    }
  }
}

// 时间选择器样式
.time-picker-container {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
  
  .date-picker, .time-picker {
    flex: 1;
    height: 80rpx;
    border: 2rpx solid #eee;
    border-radius: 12rpx;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    
    .picker-text {
      font-size: 28rpx;
      color: #333;
    }
  }
}
</style> 